package model;

import java.util.ArrayList;

public class Term {

	private final String originalTerm;
	// private String term = "";
	public String descr = "";
	public String theme = "";
	public ArrayList<NoBracesTerm> calcLog = new ArrayList<NoBracesTerm>();

	public Term(final String term, final String descr, final String theme) {
		this.originalTerm = term;
		this.descr = descr;
		this.theme = theme;
		getFastCalcLog(StringAnalyser.getOptimizedTerm(term));
	}

	private void getFastCalcLog(String term) {
		final StringPosVec firstPos = StringAnalyser.getFirstInnerTermPos(term);
		if (firstPos != null) {
			// String replacedPart=
			// StringAnalyser.getSubstringWithoutBraces(term,firstPos);
			final StringPosVec editedFirstPost = new StringPosVec(firstPos.start + 1,
					firstPos.end - 1);
			final String replacedPart = StringAnalyser.getSubTerm(term,
					editedFirstPost);
			if (StringAnalyser.noOperator(replacedPart)) {
				// here only the braces are removed ( (x)+y => x+y )
				term = StringAnalyser.replacePart(term, replacedPart, firstPos);
				// there is no need to add a new var to the calcLog because
				// replacedPart is a var itself and has a value
			} 
			else {
				String id = VarNameFactory.getNewVarName();
				term = StringAnalyser.replacePart(term, id, firstPos);
				calcLog.add(new NoBracesTerm(id,
						replacedPart));
			}

			getFastCalcLog(term);
		} else if (!StringAnalyser.noOperator(term)) {
			String id = VarNameFactory.getNewVarName(); //TODO is a new id needed??
			calcLog.add(new NoBracesTerm(id, term));
			
			//getFastCalcLog(term);
		}
	}

	@Override
	public String toString() {
		return originalTerm;
	}

	public void executeOn(final VarValueList varValueList) {
		for (int i = 0; i < calcLog.size(); i++) {
			calcLog.get(i).executeOn(varValueList);
		}
	}

	public void executeOn(final SpeedVarValueList speedVarValueList) {
		for (int i = 0; i < calcLog.size(); i++) {
			calcLog.get(i).speedExecuteOn(speedVarValueList);
		}
	}

}
